package com.plian.system.service.fr.indicatorsstdvalue;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.plian.Tools.*;
import com.plian.Tools.file.FilesUtil;
import com.plian.Tools.operation.OperationExpressionUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.dao.fr.annualreport.AnnualReportDao;
import com.plian.system.dao.fr.financeindicators.FinanceIndicatorsDao;
import com.plian.system.dao.fr.fstdvalue.FstdvalueDao;
import com.plian.system.dao.fr.gsalaryslip.GsalarySlipDao;
import com.plian.system.dao.fr.indicatorsstdvalue.IndicatorsStdvalueDao;
import com.plian.system.dao.fr.indicatorsvalue.IndicatorsValueDao;
import com.plian.system.dao.sys.excel.AutoExcelDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.entity.fr.bulletin.BulletinValue;
import com.plian.system.entity.fr.indicators.IndicatorsValue;
import com.plian.system.entity.fr.report.ReportAdjustmentRelation;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import com.plian.system.service.fr.bulletin.IBulletinValueService;
import com.plian.system.service.fr.bulletin.INewBulletinService;
import com.plian.system.service.fr.indicatorsvalue.IndicatorsValueService;
import com.plian.system.service.fr.report.IReportAdjustmentRelationService;
import com.plian.system.service.fr.report.IReportVersionService;
import com.plian.system.vo.fr.bulletin.NewBulletinVO;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 说明：指标标准值表
 */
@Service
@Transactional
public class IndicatorsStdvalueService {
    @Autowired
    IndicatorsStdvalueDao indicatorsstdvalueDao;
    @Autowired
    IndicatorsValueDao indicatorsValueDao;
    @Autowired
    FstdvalueDao fstdvalueDao;
    @Autowired
    FinanceIndicatorsDao financeindicatorsDao;
    @Autowired
    AnnualReportDao annualReportDao;//年报
    @Autowired
    GsalarySlipDao gsalarySlipDao;//预算
    @Autowired
    OrgzationDao orgzationDao;
    @Autowired
    AutoExcelDao autoExcelDao;
    @Autowired
    IndicatorsValueService indicatorsValueService;
    @Autowired
    IReportAdjustmentRelationService reportAdjustmentRelationService;
    @Autowired
    IReportVersionService reportVersionService;
    @Autowired
    INewBulletinService newBulletinService;
    @Autowired
    IBulletinValueService bulletinValueService;

    private static final Logger LOGGER = LoggerFactory.getLogger(IndicatorsStdvalueService.class);

    /**
     * 保存
     *
     * @param pd
     * @return
     */
    public ObjResult save(PageData pd) {
        try {
            PageData pe = indicatorsstdvalueDao.findrepeat(pd);
            if (pe != null && pe.getString("id") != null) {
                ObjResult objResult = new ObjResult(CommonCode.EXIST);
                objResult.setMessage("数据重复");
                return objResult;
            }
            String id = UuidUtil.get32UUID();
            pd.put("id", id);
            pd.put("createTime", new Date());
            pd.put("updateTime", new Date());
            pd.put("createUser", TokenUtil.getTokenUserId());
            pd.put("updateUser", TokenUtil.getTokenUserId());
            indicatorsstdvalueDao.save(pd);
            ObjectMapper mapper = new ObjectMapper();
            //保存从表: 标准值子表
            List<PageData> list_Fstdvalue = mapper.convertValue((List<PageData>) pd.get("listFstdvalue"), new TypeReference<List<PageData>>() {
            });
            saveFstdvalue(list_Fstdvalue, id);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            return objResult;
        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));
            return new ObjResult(CommonCode.ERROR);
        }
    }

    /**
     * 保存
     *
     * @param pd
     * @return
     */
    public void saveinport(PageData pd) {
        try {
            PageData pe = indicatorsstdvalueDao.findrepeat(pd);
            if (pe != null && pe.getString("id") != null) {
                List<String> ls = new ArrayList<String>();
                ls.add(pe.getString("id"));
                indicatorsstdvalueDao.del_ids(ls);
            }
            String id = UuidUtil.get32UUID();
            pd.put("id", id);
            pd.put("createTime", new Date());
            pd.put("updateTime", new Date());
            pd.put("createUser", TokenUtil.getTokenUserId());
            pd.put("updateUser", TokenUtil.getTokenUserId());
            indicatorsstdvalueDao.save(pd);
            ObjectMapper mapper = new ObjectMapper();
            //保存从表: 标准值子表
            List<PageData> list_Fstdvalue = (List<PageData>) pd.get("list");
            saveFstdvalue(list_Fstdvalue, id);


        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));

        }
    }

    /**
     * 修改
     *
     * @param pd
     * @return
     */
    public ObjResult edit(PageData pd) {
        try {
            PageData pe = indicatorsstdvalueDao.findrepeat(pd);
            if (pe != null && pe.getString("id") != null && !pe.getString("id").equals(pd.getString("id"))) {
                ObjResult objResult = new ObjResult(CommonCode.EXIST);
                objResult.setMessage("数据重复");
                return objResult;
            }
            String id = pd.getString("id");
            pd.put("updateTime", new Date());
            pd.put("updateUser", TokenUtil.getTokenUserId());
            indicatorsstdvalueDao.edit(pd);
            ObjectMapper mapper = new ObjectMapper();
            //修改从表: 标准值子表
            List<PageData> list_Fstdvalue = mapper.convertValue((List<PageData>) pd.get("listFstdvalue"), new TypeReference<List<PageData>>() {
            });
            fstdvalueDao.delPrenteId(id);
            saveFstdvalue(list_Fstdvalue, id);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            return objResult;
        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));
            return new ObjResult(CommonCode.ERROR);
        }
    }

    /**
     * 查询列表
     *
     * @return
     */
    public ListResult listPage(PageData pd) {
        ListResult listResult;
        try {
            boolean isPage = true;
            if (pd.containsKey("isPage")) {
                isPage = (boolean) pd.get("isPage");
            }
            Page page = new Page(isPage, pd);
            List<PageData> list = indicatorsstdvalueDao.listPage(page);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }

    /**
     * 根据id查询
     *
     * @param pd
     * @return
     */
    public ObjResult findbyid(PageData pd) {
        ObjResult objResult;
        String id = pd.getString("id");
        try {
            PageData p = indicatorsstdvalueDao.findbyid(id);
            objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }
    }

    /**
     * 数据导入
     *
     * @return
     */
    public ObjResult importExcel(@RequestParam("file") MultipartFile mf) {
        ObjResult objResult;
        List<PageData> list = new ArrayList<>();
        try {
            InputStream input = mf.getInputStream();
            HSSFWorkbook workbook = new HSSFWorkbook(input);
            HSSFSheet sheet = workbook.getSheetAt(0);
            int rows = sheet.getPhysicalNumberOfRows();
            String[] sl = {"平均值", "较低值", "较差值"};
            if (rows > 0) {
                // 有数据时才处理
                Map<Integer, String> fieldsMap = new HashMap<>();
                String fyear = "";
                // 定义一个map用于存放列的序号和field.
                for (int i = 1; i < rows; i++) {

                    if (i == 1) {
                        HSSFRow row = sheet.getRow(i);
                        HSSFCell cell = row.getCell(0);
                        UploadUtil uploadUtil = new UploadUtil();
                        fyear = uploadUtil.getCellValue(cell);
                    } else {
                        List<PageData> lp1 = new ArrayList<PageData>();
                        List<PageData> lp2 = new ArrayList<PageData>();
                        List<PageData> lp3 = new ArrayList<PageData>();
                        List<PageData> lp4 = new ArrayList<PageData>();
                        PageData pb = new PageData();
                        HSSFRow row = sheet.getRow(i);
                        PageData rowsPd = new PageData();
                        for (int j = 1; j <= row.getLastCellNum(); j++) {
                            HSSFCell cell = row.getCell(j);
                            if (cell == null) {
                                continue;
                            }
                            UploadUtil uploadUtil = new UploadUtil();
                            String c = uploadUtil.getCellValue(cell);

                            if (c == null || "非法字符".equals(c) || "未知类型".equals(c)) {
                                continue;
                            } else {
                                if (j == 1) {
                                    PageData ps = new PageData();
                                    ps.put("name", c);
                                    PageData pi = indicatorsstdvalueDao.findfindustrybyname(ps);
                                    pb.put("findustry", pi.getString("findustry"));
                                } else if (j == 2) {
                                    pb.put("industryScale", c);
                                } else {
                                    if (pb != null && Tools.notEmpty(pb.getString("industryScale"))) {
                                        if (j >= 3 && j <= 5) {
                                            PageData pz = new PageData();
                                            pz.put("valueName", sl[j - 3]);
                                            pz.put("standardValues", c);
                                            lp1.add(pz);
                                        }
                                        if (j >= 6 && j <= 8) {
                                            PageData pz = new PageData();
                                            pz.put("valueName", sl[j - 6]);
                                            pz.put("standardValues", c);
                                            lp2.add(pz);
                                        }
                                        if (j >= 9 && j <= 11) {
                                            PageData pz = new PageData();
                                            pz.put("valueName", sl[j - 9]);
                                            pz.put("standardValues", c);
                                            lp3.add(pz);
                                        }
                                        if (j >= 12 && j <= 14) {
                                            PageData pz = new PageData();
                                            pz.put("valueName", sl[j - 12]);
                                            pz.put("standardValues", c);
                                            lp4.add(pz);
                                        }
                                    }
                                }
                            }
                        }
                        if (lp1 != null && lp1.size() > 0) {
                            String type = "G1";
                            PageData p1 = integration(pb, lp1, fyear, type);
                            saveinport(p1);
                        }
                        if (lp2 != null && lp2.size() > 0) {
                            String type = "G2";
                            PageData p2 = integration(pb, lp2, fyear, type);
                            saveinport(p2);
                        }
                        if (lp3 != null && lp3.size() > 0) {
                            String type = "G3";
                            PageData p3 = integration(pb, lp3, fyear, type);
                            saveinport(p3);
                        }
                        if (lp4 != null && lp4.size() > 0) {
                            String type = "G4";
                            PageData p4 = integration(pb, lp4, fyear, type);
                            saveinport(p4);
                        }


                    }


                }
            } else {
                PageData msg = new PageData();
                msg.put("msg", "Excel内没有数据！");
                list.add(msg);
            }
            objResult = new ObjResult(CommonCode.SUCCESS);
            return objResult;
        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));
             LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }
    }

    public PageData integration(PageData pb, List<PageData> lp, String fyear, String type) throws Exception {
        PageData p = new PageData();
        p.putAll(pb);
        PageData pf = financeindicatorsDao.findByCode(type);
        p.put("indicatorsId", pf.getString("id"));
        p.put("fname", pf.getString("name"));
        p.put("fyear", fyear);
        p.put("list", lp);
        return p;
    }

    public ObjResult del_ids(List<String> ids) {
        try {
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            indicatorsstdvalueDao.del_ids(ids);
            return objResult;
        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));
            return new ObjResult(CommonCode.ERROR);
        }
    }

    public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
        try {
//            String exlPath = "exceldemo" + File.separator;
//            ClassPathResource classPathResource = new ClassPathResource(exlPath);
//            String ftlPath = classPathResource.getPath();
//            FilesUtil.DownFile1("指标标准值导入.xls", ftlPath, response);
            //20241225 zsk 原先的写法获取不到Resource的路径
            String exlPath = "exceldemo";
            URL url = getClass().getClassLoader().getResource(exlPath);//2024-12-23 换一种写法要不然获取不到路径
            String ftlPath= url.getPath();
            FilesUtil.DownFile1("指标标准值导入.xls", ftlPath, response);
        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));
        }
    }

    /**
     * 保存
     *
     * @param list    从表列表
     * @param prentId 主键id
     */
    private void saveFstdvalue(List<PageData> list, String prentId) throws Exception {
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("indicatorsStdvalueId", prentId);
                pageData.put("orderNumber", list.indexOf(pageData));
                pageData.put("id", UuidUtil.get32UUID());
            }
            fstdvalueDao.saveAll(list);
        }
    }

    /**
     * 查询主表，从表数据
     *
     * @param pd
     * @return
     */
    public ObjResult findidAll(PageData pd) {
        String id = pd.getString("id");
        ObjResult objResult;
        try {
            //主表信息
            PageData p = indicatorsstdvalueDao.findbyid(id);
            List<PageData> list_Fstdvalue = fstdvalueDao.find_parentId(id);
            p.put("listFstdvalue", list_Fstdvalue);
            objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
        }
        return objResult;
    }

    private void setValue(List<NewBulletinVO> voList, String month, String orgId, String fieldName, IndicatorsValue indicatorsValue){
        for (NewBulletinVO vo : voList){
            if(orgId.equals(vo.getOrgId()) && vo.getMonth().equals(month)){
                for (BulletinValue value : vo.getBulletinValues()){
                    if (fieldName.equals(value.getColumnName())){
                        indicatorsValue.setFvalue(value.getMonthAmount() != null ? value.getMonthAmount() : new BigDecimal(0));
                        break;
                    }
                    if((fieldName).equals("LAST_" + value.getColumnName())){
                        indicatorsValue.setFvalue(value.getLastYearMonthAmount() != null ? value.getLastYearMonthAmount() : new BigDecimal(0));
                        break;
                    }
                    if((fieldName).equals("SUM_" + value.getColumnName())){
                        indicatorsValue.setFvalue(value.getYearAmount() != null ? value.getYearAmount() : new BigDecimal(0));
                        break;
                    }
                }
            }
        }
    }


    /**
     * 计算指标
     */
    @Transient
    public void calculation() {
        PageData pd = new PageData();
        String yearStr = DateUtil.format(DateUtil.minusMonths(DateUtil.now(), 1)
                , DateUtil.PATTERN_YEAR);
        pd.put("year", yearStr);
        String version = reportVersionService.getVersion(yearStr);
        Page page = new Page(false, pd);
        try {
//            //指标
            List<PageData> l = financeindicatorsDao.listPage(page);
            //有公式的指标
            List<PageData> formula_lis = new ArrayList<>();
            //取原值的指标
            List<PageData> formula_lis1 = new ArrayList<>();

            for (PageData pageData : l) {
                if ("0".equals(pageData.getString("type"))) {
                    formula_lis1.add(pageData);
                }
                if ("1".equals(pageData.getString("type"))) {
                    formula_lis.add(pageData);
                }
            }

            OperationExpressionUtil operationExpressionUtil = new OperationExpressionUtil();

            //按照数据源分组
            Map<String, List<PageData>> gDataSource = formula_lis1.stream().
                    filter(item -> Tools.notEmpty(item.getString("dataSource"))).
                    collect(Collectors.groupingBy(e -> e.getString("dataSource")));

            List<PageData> orgs = orgzationDao.listUnFictitious();

            /**
             * 预算和调整关系
             */
            List<ReportAdjustmentRelation> reportAdjustmentRelations = reportAdjustmentRelationService
                    .list(new LambdaQueryWrapper<ReportAdjustmentRelation>().eq(ReportAdjustmentRelation::getVersion, version));
            Map<String, ReportAdjustmentRelation> relationMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(reportAdjustmentRelations)){
               relationMap = reportAdjustmentRelations.stream()
                        .collect(Collectors
                                .toMap(adjustmentRelation -> adjustmentRelation.getReportTableName()
                                        + "_" + adjustmentRelation.getReportColumns() + "_" + adjustmentRelation.getReportLines(),
                                        adjustmentRelation -> adjustmentRelation, (a, b) -> a));
            }

            //处理的单位数据
            List<IndicatorsValue> indicatorsValues = new ArrayList<>();
            int y = Integer.valueOf(yearStr);
            int year[] = {y};
//            无公式处理数据
            for (String s : gDataSource.keySet()) {
                List<PageData> list = gDataSource.get(s);
                //预算
                if ("0".equals(s)) {
                    PageData p_r = new PageData();
                    p_r.put("years", year);
                    for (PageData pageData : list) {
                        String fieldName = pageData.getString("fieldName");
                        p_r.put("fieldName", fieldName);
                        p_r.put("lines", pageData.getString("lines"));
                        p_r.put("columns", pageData.getString("columns"));
                        p_r.put("tableName", pageData.getString("tabName"));
                        List<PageData> p = gsalarySlipDao.getFinancialDate(p_r);
                        List<PageData> p2 = gsalarySlipDao.getGroupFinancialDate(p_r);

                        String key = pageData.getString("tabName") + "_" +  pageData.getString("columns") + "_" + pageData.getString("lines");
                        if (relationMap.containsKey(key)){
                            ReportAdjustmentRelation adjustmentInfo = relationMap.get(key);
                            p_r.put("lines", adjustmentInfo.getAdjustmentLines());
                            p_r.put("columns", adjustmentInfo.getAdjustmentColumns());
                            p_r.put("tableName", adjustmentInfo.getAdjustmentTableName());
                        }
                        List<PageData> adtP = gsalarySlipDao.getAdjustmentFinancialDate(p_r);
                        List<PageData> adtP2 = gsalarySlipDao.getAdjustmentGroupFinancialDate(p_r);
                        for (PageData org : orgs) {
                            IndicatorsValue indicatorsValue = new IndicatorsValue();
                            IndicatorsValue indicatorsValue2 = new IndicatorsValue();
                            indicatorsValue.setOrgId(org.getString("id"));
                            indicatorsValue.setFvalue(new BigDecimal(0));
                            for (PageData data : p) {
                                if (org.getString("id").equals(data.getString("orgId"))) {
                                    if (Tools.notEmpty(data.getString(fieldName))) {
                                        indicatorsValue.setFvalue(new BigDecimal(StringUtil.cleanChars(data.getString(fieldName))));
                                    }
                                }
                            }

                            for (PageData data : adtP) {
                                if (org.getString("id").equals(data.getString("orgId"))) {
                                    if (Tools.notEmpty(data.getString(fieldName))) {
                                        indicatorsValue.setFvalue(new BigDecimal(StringUtil.cleanChars(data.getString(fieldName))));
                                    }
                                }
                            }
                            indicatorsValue.setFyear(String.valueOf(y));
                            indicatorsValue.setIsGroup("0");
                            indicatorsValue.setFmonth("00");
                            indicatorsValue.setCreateTime(new Date());
                            indicatorsValue.setIndicatorsId(pageData.getString("id"));
                            indicatorsValue.setCode(pageData.getString("code"));
                            indicatorsValue.setId(UuidUtil.get32UUID());
                            indicatorsValues.add(indicatorsValue);

                            if ("0".equals(org.getString("typeCode"))|| "3".equals(org.getString("typeCode"))) {
                                BeanUtils.copyProperties(indicatorsValue, indicatorsValue2);
                                indicatorsValue2.setId(UuidUtil.get32UUID());
                                indicatorsValue2.setIsGroup("1");
                                indicatorsValue2.setFvalue(new BigDecimal(0));
                                for (PageData data2 : p2) {
                                    if (org.getString("id").equals(data2.getString("orgId"))) {
                                        if (Tools.notEmpty(data2.getString(fieldName))) {
                                            indicatorsValue2.setFvalue(new BigDecimal(StringUtil.cleanChars(data2.getString(fieldName))));
                                        }
                                    }
                                }

                                for (PageData data2 : adtP2) {
                                    if (org.getString("id").equals(data2.getString("orgId"))) {
                                        if (Tools.notEmpty(data2.getString(fieldName))) {
                                            indicatorsValue2.setFvalue(new BigDecimal(StringUtil.cleanChars(data2.getString(fieldName))));
                                        }
                                    }
                                }
                                indicatorsValues.add(indicatorsValue2);
                            }

                            //均分12份
                            BigDecimal value = indicatorsValue.getFvalue();
                            BigDecimal b_v = value.divide(new BigDecimal("12"), 6, BigDecimal.ROUND_HALF_UP);
                            BigDecimal value2;
                            BigDecimal b_v2 = new BigDecimal("0");
                            if ("0".equals(org.getString("typeCode"))|| "3".equals(org.getString("typeCode"))) {
                                value2 = indicatorsValue2.getFvalue();
                                b_v2 = value2.divide(new BigDecimal("12"), 6, BigDecimal.ROUND_HALF_UP);
                            }
                            for (int i = 1; i <= 12; i++) {
                                IndicatorsValue indicatorsValue1 = new IndicatorsValue();

                                String m = String.valueOf(i);
                                if (i < 10) {
                                    m = "0" + i;
                                }
                                BeanUtils.copyProperties(indicatorsValue, indicatorsValue1);
                                indicatorsValue1.setFmonth(m);
                                indicatorsValue1.setFvalue(b_v);
                                indicatorsValue1.setId(UuidUtil.get32UUID());
                                indicatorsValues.add(indicatorsValue1);
                                if ("0".equals(org.getString("typeCode"))|| "3".equals(org.getString("typeCode"))) {
                                    IndicatorsValue indicatorsValue3 = new IndicatorsValue();
                                    BeanUtils.copyProperties(indicatorsValue1, indicatorsValue3);
                                    indicatorsValue3.setFvalue(b_v2);
                                    indicatorsValue3.setIsGroup("1");
                                    indicatorsValue3.setId(UuidUtil.get32UUID());
                                    indicatorsValues.add(indicatorsValue3);
                                }

                            }

                        }
                    }
                } else
                    //年报
                    if ("1".equals(s)) {
                        PageData p1 = new PageData();
                        p1.put("years", year);
                        List<String> list1 = new ArrayList<>();
                        for (PageData pageData : list) {
                            list1.add(pageData.getString("fieldName"));
                        }
                        p1.put("fieldName", list1);
                        List<PageData> l1 = annualReportDao.getFinancialDate(p1);
                        List<PageData> l2 = annualReportDao.getGorupFinancialDate(p1);
                        for (PageData org : orgs) {
                            for (PageData pageData : list) {
                                IndicatorsValue indicatorsValue = new IndicatorsValue();
                                IndicatorsValue indicatorsValue2 = new IndicatorsValue();
                                indicatorsValue.setOrgId(org.getString("id"));
                                indicatorsValue.setFvalue(new BigDecimal(0));
                                indicatorsValue.setFyear(String.valueOf(y));
                                indicatorsValue.setIsGroup("0");
                                indicatorsValue.setFmonth("00");
                                indicatorsValue.setCreateTime(new Date());
                                indicatorsValue.setIndicatorsId(pageData.getString("id"));
                                indicatorsValue.setCode(pageData.getString("code"));
                                indicatorsValue.setId(UuidUtil.get32UUID());


                                for (PageData data : l1) {
                                    if (org.getString("id").equals(data.getString("orgId"))) {
                                        String fieldName = pageData.getString("fieldName");
                                        if (Tools.notEmpty(data.getString(fieldName))) {
                                            indicatorsValue.setFvalue(new BigDecimal(StringUtil.cleanChars(data.getString(fieldName))));
                                            break;
                                        }
                                    }
                                }
                                indicatorsValues.add(indicatorsValue);

                                if ("0".equals(org.getString("typeCode"))|| "3".equals(org.getString("typeCode"))) {
                                    BeanUtils.copyProperties(indicatorsValue, indicatorsValue2);
                                    indicatorsValue2.setId(UuidUtil.get32UUID());
                                    indicatorsValue2.setIsGroup("1");
                                    indicatorsValue2.setFvalue(new BigDecimal(0));
                                    for (PageData data : l2) {
                                        if (org.getString("id").equals(data.getString("orgId"))) {
                                            String fieldName = pageData.getString("fieldName");
                                            if (Tools.notEmpty(data.getString(fieldName))) {
                                                indicatorsValue2.setFvalue(new BigDecimal(StringUtil.cleanChars(data.getString(fieldName))));
                                                break;
                                            }
                                        }
                                    }
                                    indicatorsValues.add(indicatorsValue2);
                                }

                                //均分12份
                                BigDecimal value = indicatorsValue.getFvalue();
                                BigDecimal b_v = value.divide(new BigDecimal("12"), 6, BigDecimal.ROUND_HALF_UP);
                                BigDecimal value2;
                                BigDecimal b_v2 = new BigDecimal("0");
                                if ("0".equals(org.getString("typeCode"))|| "3".equals(org.getString("typeCode"))) {
                                    value2 = indicatorsValue2.getFvalue();
                                    b_v2 = value2.divide(new BigDecimal("12"), 6, BigDecimal.ROUND_HALF_UP);
                                }
                                for (int i = 1; i <= 12; i++) {
                                    String m = String.valueOf(i);
                                    if (i < 10) {
                                        m = "0" + i;
                                    }
                                    IndicatorsValue indicatorsValue1 = new IndicatorsValue();
                                    BeanUtils.copyProperties(indicatorsValue, indicatorsValue1);
                                    indicatorsValue1.setFmonth(m);
                                    indicatorsValue1.setFvalue(b_v);
                                    indicatorsValue1.setId(UuidUtil.get32UUID());
                                    indicatorsValues.add(indicatorsValue1);

                                    if ("0".equals(org.getString("typeCode"))|| "3".equals(org.getString("typeCode"))) {
                                        IndicatorsValue indicatorsValue3 = new IndicatorsValue();
                                        BeanUtils.copyProperties(indicatorsValue1, indicatorsValue3);
                                        indicatorsValue3.setFvalue(b_v2);
                                        indicatorsValue3.setIsGroup("1");
                                        indicatorsValue3.setId(UuidUtil.get32UUID());
                                        indicatorsValues.add(indicatorsValue3);

                                    }
                                }
                            }
                        }
                    }
                    else
                        //月度
                        if ("2".equals(s)) {
                            PageData p2 = new PageData();
                            p2.put("years", year);
                            List<String> list1 = new ArrayList<>();
                            for (PageData pageData : list) {
                                list1.add(pageData.getString("fieldName"));
                            }
                            p2.put("fieldName", list1);

                            List<NewBulletinVO> l1 = newBulletinService.getSingleListByYear(yearStr, null);
                            List<NewBulletinVO> l2 = newBulletinService.getGroupListByYear(yearStr, null);
                            for (PageData org : orgs) {
                                for (PageData pageData : list) {
                                    BigDecimal sum = new BigDecimal("0");
                                    BigDecimal sum2 = new BigDecimal("0");
                                    String orgId = org.getString("id");
                                    for (int i = 1; i <= 12; i++) {
                                        String m = String.valueOf(i);
                                        if (i < 10) {
                                            m = "0" + i;
                                        }
                                        IndicatorsValue indicatorsValue = new IndicatorsValue();
                                        indicatorsValue.setOrgId(org.getString("id"));
                                        indicatorsValue.setFvalue(new BigDecimal(0));
                                        indicatorsValue.setFyear(String.valueOf(y));
                                        indicatorsValue.setIsGroup("0");
                                        indicatorsValue.setFmonth(m);
                                        indicatorsValue.setCreateTime(new Date());
                                        indicatorsValue.setIndicatorsId(pageData.getString("id"));
                                        indicatorsValue.setCode(pageData.getString("code"));
                                        indicatorsValue.setId(UuidUtil.get32UUID());
                                        setValue(l1, m, orgId, pageData.getString("fieldName"), indicatorsValue);


                                        if ("0".equals(org.getString("typeCode"))|| "3".equals(org.getString("typeCode"))) {
                                            IndicatorsValue indicatorsValue2 = new IndicatorsValue();
                                            BeanUtils.copyProperties(indicatorsValue, indicatorsValue2);
                                            indicatorsValue2.setId(UuidUtil.get32UUID());
                                            indicatorsValue2.setIsGroup("1");
                                            setValue(l2, m, orgId, pageData.getString("fieldName"), indicatorsValue2);
                                            indicatorsValues.add(indicatorsValue2);
                                            sum2 = sum2.add(indicatorsValue2.getFvalue());
                                        }
                                        indicatorsValues.add(indicatorsValue);
                                        sum = sum.add(indicatorsValue.getFvalue());
                                    }
                                    IndicatorsValue indicatorsValue1 = new IndicatorsValue();

                                    indicatorsValue1.setOrgId(org.getString("id"));
                                    indicatorsValue1.setFvalue(sum);
                                    indicatorsValue1.setFyear(String.valueOf(y));
                                    indicatorsValue1.setIsGroup("0");
                                    indicatorsValue1.setFmonth("00");
                                    indicatorsValue1.setCreateTime(new Date());
                                    indicatorsValue1.setIndicatorsId(pageData.getString("id"));
                                    indicatorsValue1.setCode(pageData.getString("code"));
                                    indicatorsValue1.setId(UuidUtil.get32UUID());

                                    if ("0".equals(org.getString("typeCode"))|| "3".equals(org.getString("typeCode"))) {
                                        IndicatorsValue indicatorsValue3 = new IndicatorsValue();
                                        BeanUtils.copyProperties(indicatorsValue1, indicatorsValue3);
                                        indicatorsValue3.setId(UuidUtil.get32UUID());
                                        indicatorsValue3.setIsGroup("1");
                                        indicatorsValue3.setFvalue(sum2);
                                        indicatorsValues.add(indicatorsValue3);
                                    }
                                    indicatorsValues.add(indicatorsValue1);

                                }
                            }
                        } else
                            if ("3".equals(s)) {
                            PageData p_r = new PageData();
                            p_r.put("year", yearStr);
                            p_r.put("years", year);
                            for (PageData pageData : list) {
                                String fieldName = pageData.getString("fieldName");
                                p_r.put("fieldName", fieldName);
                                p_r.put("lines", pageData.getString("lines"));
                                p_r.put("columns", pageData.getString("columns"));
                                p_r.put("code", pageData.getString("excelCode"));
                                p_r.put("tableName", pageData.getString("tabName"));
                                List<PageData> p = autoExcelDao.getFinancialDate(p_r);
                                for (PageData org : orgs) {
                                    IndicatorsValue indicatorsValue = new IndicatorsValue();
                                    indicatorsValue.setOrgId(org.getString("id"));
                                    indicatorsValue.setFvalue(new BigDecimal(0));
                                    for (PageData data : p) {
                                        if (org.getString("id").equals(data.getString("orgId"))) {
                                            if (Tools.notEmpty(data.getString(fieldName))) {
                                                indicatorsValue.setFvalue(new BigDecimal(StringUtil.cleanChars(data.getString(fieldName))));
                                            }
                                        }
                                    }
                                    indicatorsValue.setFyear(String.valueOf(y));
                                    indicatorsValue.setIsGroup("0");
                                    indicatorsValue.setFmonth("00");
                                    indicatorsValue.setCreateTime(new Date());
                                    indicatorsValue.setIndicatorsId(pageData.getString("id"));
                                    indicatorsValue.setCode(pageData.getString("code"));
                                    indicatorsValue.setId(UuidUtil.get32UUID());
                                    indicatorsValues.add(indicatorsValue);

                                    //均分12份
                                    BigDecimal value = indicatorsValue.getFvalue();
                                    BigDecimal b_v = value.divide(new BigDecimal("12"), 6, BigDecimal.ROUND_HALF_UP);
                                    for (int i = 1; i <= 12; i++) {
                                        IndicatorsValue indicatorsValue2 = new IndicatorsValue();
                                        BeanUtils.copyProperties(indicatorsValue, indicatorsValue2);
                                        String m = String.valueOf(i);
                                        if (i < 10) {
                                            m = "0" + i;
                                        }
                                        indicatorsValue2.setId(UuidUtil.get32UUID());
                                        indicatorsValue2.setIsGroup("0");
                                        indicatorsValue2.setFmonth(m);
                                        indicatorsValue2.setFvalue(b_v);
                                        indicatorsValues.add(indicatorsValue2);
                                    }

                                }
                            }
                        }
            }

            if (formula_lis != null && formula_lis.size() > 0) {
                //根据处理数据单位分组
                Map<String, List<IndicatorsValue>> g_v = indicatorsValues.stream().
                        filter(item -> Tools.notEmpty(item.getOrgId())&& Tools.notEmpty(item.getIsGroup())).
                        collect(Collectors.groupingBy(e -> e.getOrgId()+'-'+e.getIsGroup()));

                for (String s : g_v.keySet()) {
                    List<IndicatorsValue> list = g_v.get(s);

                    for (int i = 0; i <= 12; i++) {
                        String m = String.valueOf(i);
                        if (i < 10) {
                            m = "0" + i;
                        }
                        //公式取值用
                        PageData p = new PageData();
                        for (IndicatorsValue p1 : list) {
                            if (p1.getFmonth().equals(m)) {
                                p.put(p1.getCode(), p1.getFvalue());
                            }

                        }

                        for (PageData v : formula_lis) {
                            IndicatorsValue indicatorsValue = new IndicatorsValue();
                            String fvalue = operationExpressionUtil.operation(v.getString("formula"), p, 6, BigDecimal.ROUND_HALF_UP);
                            indicatorsValue.setFvalue(new BigDecimal(fvalue));
                            indicatorsValue.setOrgId(s.substring(0,s.length()-2));
                            indicatorsValue.setIsGroup(s.substring(s.length()-1));
                            indicatorsValue.setCreateTime(new Date());
                            indicatorsValue.setIndicatorsId(v.getString("id"));
                            indicatorsValue.setFyear(String.valueOf(y));
                            indicatorsValue.setFmonth(m);
                            indicatorsValue.setId(UuidUtil.get32UUID());
                            indicatorsValues.add(indicatorsValue);
                        }

                    }

                }
            }
                if (indicatorsValues != null && indicatorsValues.size() > 0) {
                    indicatorsValueDao.del_year(String.valueOf(y));
                    indicatorsValueService.saveBatch(indicatorsValues);
                }

        } catch (Exception e) {
             LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException();
        }
    }
}
